import { IPSAppDataEntity, IPSAppDEView, IPSAppView, IPSAppViewRef, IPSTreeExpBar } from '@ibiz/dynamic-model-api';
import { AppExpBarCtrlController } from './app-exp-bar-ctrl-controller';
import { AppExpBarCtrlEvents, IMobTreeExpBarController, IUIDataParam, MobTreeEvents } from '../../../interface';
import { Util } from '../../../util/util';
import { ViewTool } from '../../../util/view-tool';

export class MobTreeExpBarController extends AppExpBarCtrlController implements IMobTreeExpBarController {

  /**
   * 移动端树导航部件实例
   *
   * @public
   * @type { IPSDEMobTreeExpBar }
   * @memberof MobTreeExpBarController
   */
  public controlInstance!: IPSTreeExpBar;

  /**
   * @description 处理部件事件
   * @param {string} controlname
   * @param {string} action
   * @param {*} data
   * @memberof MobTreeExpBarController
   */
  public handleCtrlEvent(controlname: string, action: string, data: any) {
    if (controlname === this.xDataControlName && action == MobTreeEvents.SELECT_CHANGE) {
      this.onSelectionChange(data);
    } else {
      super.handleCtrlEvent(controlname, action, data);
    }
  }

  /**
   * @description 选中数据变化
   * @protected
   * @param {IUIDataParam} uiDataParam UI数据
   * @return {*}  {void}
   * @memberof AppExpBarCtrlController
   */
  protected async onSelectionChange(uiDataParam: IUIDataParam) {
    const args = uiDataParam?.data || [];
    if (args.length === 0) {
      this.calcToolbarItemState(true);
      return;
    }
    const arg: any = args[0];
    if (!arg.id) {
      return;
    }
    const nodetype = arg.id.split(';')[0];
    const refview: any = await this.getExpItemView({ nodetype: nodetype });

    if (!refview) {
      this.calcToolbarItemState(true);
      return;
    }
    let { tempContext, tempViewparam } = this.computeNavParams(arg);
    this.openExplorerView(refview.viewModelData, args, tempContext, tempViewparam)
    this.selection = {};
    this.calcToolbarItemState(false);
  }


  /**
   * 计算导航参数
   * 
   * @param arg  选中数据
   * @memberof TreeExpBarControlBase
   */
  public computeNavParams(arg: any) {
    let tempContext: any = {};
    let tempViewparam: any = {};
    if (arg && arg.navfilter) {
      Object.defineProperty(tempViewparam, arg.navfilter, {
        value: arg.srfkey,
        writable: true,
        enumerable: true,
        configurable: true
      })
    }
    Object.assign(tempContext, Util.deepCopy(this.context));
    if (arg.srfappctx) {
      Object.assign(tempContext, Util.deepCopy(arg.srfappctx));
    }
    if (arg.srfparentdename) {
      Object.assign(tempContext, { srfparentdename: arg.srfparentdename });
    }
    if (arg.srfparentdemapname) {
      Object.assign(tempContext, { srfparentdemapname: arg.srfparentdemapname });
    }
    if (arg.srfparentkey) {
      Object.assign(tempContext, { srfparentkey: arg.srfparentkey });
    }
    // 计算导航上下文
    if (arg && arg.navigateContext && Object.keys(arg.navigateContext).length > 0) {
      let tempData: any = arg.curData ? arg.curData : {};
      Object.assign(tempData, arg);
      let _context = Util.computedNavData(tempData, tempContext, tempViewparam, arg.navigateContext);
      Object.assign(tempContext, _context);
    }
    // 计算导航参数
    if (arg && arg.navigateParams && Object.keys(arg.navigateParams).length > 0) {
      let tempData: any = arg.curData ? arg.curData : {};
      Object.assign(tempData, arg);
      let _params = Util.computedNavData(tempData, tempContext, tempViewparam, arg.navigateParams);
      Object.assign(tempViewparam, _params);
    }
    return { tempContext, tempViewparam };
  }

  /**
   * 获取关系项视图
   *
   * @param {*} [arg={}] 额外参数
   * @returns {*}
   * @memberof TreeExpBarControlBase
   */
  public async getExpItemView(arg: any = {}) {
    let expmode = 'EXPITEM:' + arg.nodetype.toUpperCase();
    if (this.controlInstance?.getPSAppViewRefs()) {
      for (let viewRef of (this.controlInstance?.getPSAppViewRefs()) as IPSAppViewRef[]) {
        if (Object.is(expmode, viewRef.name.toUpperCase())) {
          let view = {
            viewModelData: viewRef.getRefPSAppView(),
            parentdata: viewRef.parentDataJO || {},
            deKeyField: viewRef.getRefPSAppView()?.getPSAppDataEntity()?.codeName?.toLowerCase(),
          }
          await view.viewModelData?.fill();
          return view;
        }
      }
    }
    return null;
  }

  /**
   * 打开视图导航视图
   *
   * @param {IPSDEChartSeries} seriesItem
   * @param {*} tempContext
   * @param {*} args
   * @memberof MobChartExpBarController
   */
  async openExplorerView(explorerView: IPSAppView, args: any, tempContext: any, tempViewParam: any) {
    let deResParameters: any[] = [];
    let parameters: any[] = [];
    if (!explorerView?.isFill) {
      await explorerView?.fill(true);
    }
    if (explorerView?.getPSAppDataEntity()) {
      deResParameters = Util.formatAppDERSPath(tempContext, (explorerView as IPSAppDEView)?.getPSAppDERSPaths());
    }
    if (explorerView?.getPSAppDataEntity()) {
      deResParameters = Util.formatAppDERSPath(tempContext, (explorerView as IPSAppDEView)?.getPSAppDERSPaths());
    }
    if (explorerView?.getPSAppDataEntity()) {
      parameters = [
        {
          pathName: Util.srfpluralize(
            (explorerView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName,
          ).toLowerCase(),
          parameterName: (explorerView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName.toLowerCase(),
        },
        {
          pathName: 'views',
          parameterName: ((explorerView as IPSAppDEView).getPSDEViewCodeName() as string).toLowerCase(),
        },
      ];
    } else {
      parameters = [{ pathName: 'views', parameterName: explorerView?.codeName.toLowerCase() }];
    }
    const routePath = ViewTool.buildUpRoutePath(tempContext, deResParameters, parameters, args, tempViewParam);
    App.getOpenViewService().openView(routePath);
  }
}
